package org.jeecg.modules.filemanage.util;


import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Component
public class CodeUtils {

    @Resource
    private RedisUtil redisUtil;

    public  String createCode(String headCode){
        String res = "",head="",tail="",today= "";

        StringBuilder sb =new StringBuilder();
        if(headCode == null || headCode.isEmpty()) {
            //头部为空则生成普通编码

        }else{
            //生成指定头部编码
            List<String> list;
            if(headCode.contains("_")) {
                list = Arrays.asList(headCode.split("_"));
            }else{
                list = Arrays.asList(headCode);
            }
            if(list.size()>0)
                head =list.get(0);
            if(list.size()>1)
                tail = list.get(1);
            sb.append(head).append("-");
        }
        today = DateUtils.getDate("yyyyMMdd");
        sb.append(today);
        sb.append("-");
        //拼接流水号

        String rediesKey = head+today;
            try {
                boolean isKey = redisUtil.hasKey(rediesKey);
                if (isKey) {
                    sb.append(redisUtil.get(rediesKey));
                    redisUtil.incr(rediesKey, 1);
                } else {
                    //获取当前时间小时数
                    int dayHour = Integer.valueOf(DateUtils.getDate("HH:mm").split(":")[0]);
                    int dayMin = Integer.valueOf(DateUtils.getDate("HH:mm").split(":")[1]);
                    redisUtil.set(rediesKey, 2, (23 - dayHour) * 3600 + (60 - dayMin) * 60);//当日过期
                    sb.append("1");
                }
            }
            catch (Exception e){
                e.printStackTrace();
                res="redis对象异常，生成失败";
                return res;
            }
        sb.append(tail);
        res = sb.toString();
        return res;
    }
}
